<?php

namespace App\Jobs;

use App\Events\OrderComputedDistribution;
use App\Models\Order;
use App\Service\MiniProgramService;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class AutoReceipt implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $orderId;

    public $shipped;

    protected $template = 'SvMc5QEuouaZXTrgyEyIVidrOEaGnYB-f6dG8eEw0js';

    // 分享着
    public $sharedUser;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($id, $shipped, $user)
    {
        $this->orderId = $id;
        $this->shipped = $shipped;
        $this->sharedUser = $user;
    }

    /**
     * 自动收货
     */
    public function handle()
    {
        $order = Order::find($this->orderId);
        if (is_null($order))return;
        // 待收货才进行任务
        Log::info('进入自动收货->'.Order::$shipStatusMap[$order->ship_status] ?? 0);
        if ($order && $order->ship_status == Order::SHIP_STATUS_DELIVERED) {
            // 自动收货
            $order->update([
                'ship_status' => Order::SHIP_STATUS_RECEIVED,
                'confirmed_at' => now()
            ]);
            // 发送自动收货提醒，并送券唤起
            $data = [
                'keyword1' => $order->order_sn,
                'keyword3' => $order->productName,
                'keyword2' => Order::$shipStatusMap[$order->ship_status] ?? '已完成',
                'keyword4' => $order->total_amount,
                'keyword5' => now(),
                'keyword6' => Carbon::parse($order->created_at)->toDateTimeString(),
                'keyword7' => '该订单已经自动确认收货，如果您未收到货物，请联系葫芦家商城客服',
            ];
            $user = $order->user()->first();
            $msg = app(MiniProgramService::class);
            $extra = $order->extra;
            $msg->sendTemplateMsg(
                $user->wx_mini_openid,
                $this->template,
                $extra['prepayid'],
                '/pages/orderDetail/orderDetail?order_id=' . $order->id,
                $data
            );
            // 自动分销
            if ($this->sharedUser instanceof User) {
                Log::info('自动收货进入分销');
                event(new OrderComputedDistribution($order, $this->sharedUser,2));
            }
            Log::info('自动收货结束->'.Order::$shipStatusMap[$order->ship_status] ?? 0);
        } else {
            Log::info('自动收货失败');
        }
    }
}
